package org.vergil.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;

@Component
public class TestWebSocketHandle extends AbstractWebSocketHandler {

    private static Logger log = LoggerFactory.getLogger(TestWebSocketHandle.class);

    private static ArrayList<WebSocketSession> sessionList = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("socket connection ....");
        sessionList.add(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.info("handle message ...{}", message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        log.info("websocket connection closed......");
        sessionList.remove(session);
    }

    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public static void sendMessageToUsers(String message) {
        TextMessage textMessage = new TextMessage(message);
        sessionList.forEach(webSocketSession -> {
            if (webSocketSession.isOpen()) {
                try {
                    webSocketSession.sendMessage(textMessage);
                } catch (IOException e) {
                    log.error("send message error", e);
                }
            }
        });

    }

//    /**
//     * 给某个用户发送消息
//     *
//     * @param userName
//     * @param message
//     */
//    public void sendMessageToUser(String userName, String  message) {
//        TextMessage textMessage = new TextMessage(message);
//        sessionList.stream().filter(webSocketSession -> webSocketSession.)
//    }
}
